var http = require('../service/http')
var config = require('../config/config.js').config
var api = require('../service/api.js')
import {URL, connection, express} from '../routes/_comm'

const sql = 'SELECT * FROM userinfo';
const addSql = 'INSERT INTO userinfo(openId,info,lastTime) VALUES(?,?,?)';
const updateSql = `UPDATE userinfo SET info = ?,lastTime = ? WHERE openId = ?`;
const selectByOpenIdSql = `SELECT * FROM userinfo WHERE openId = ?`;

//用户点击按钮进入商城
exports.shop = function (req, res) {
  //进入商城首先获取用户权限
  api.accessToken_openId(req, res).then(function (data) {
    // 获取权限之后获取用户信息然后将首页展示给用户
    console.log('DATA:', data)
    // res.render('shop', {name: data.info.nickname, img: data.info.headimgurl})
    // res.json({
    //   name: data.info.nickname,
    //   img: data.info.headimgurl
    // })
    let openIdExist = null
    let openId = data.openId;
    /**
     * 查询是否存在 OpenId
     */
    connection.query(selectByOpenIdSql, [openId], (err, result) => {
      if (err) {
        console.log('[SELECT ERROR] - ', err.message);
      } else {
        openIdExist = (result.length > 0)
        console.log('openIdExist:', openIdExist)
        if (openIdExist !== null) {
          if (openIdExist) {
            /**
             * 更新
             */
            connection.query(updateSql, [JSON.stringify(data.info), (new Date()).getTime(), openId], (err, result) => {
              console.log('UPDATE result:', result)
              if (err) {
                console.log('[UPDATE ERROR] - ', err.message);
              } else {
                console.log('[UPDATE SUCCESS]');
              }
            });
          } else {
            /**
             * 新建
             */
            let addSqlParams = [openId, JSON.stringify(data.info), (new Date()).getTime()];
            connection.query(addSql, addSqlParams, (err, result) => {
              console.log('result', result)
              if (err) {
                console.log('[INSERT ERROR] - ', err.message);
              } else {
                console.log('[INSERT SUCCESS]');
              }
            });
          }
        }
        res.redirect(`http://syangwechar.ngrok.xiaomiqiu.cn/shop/${data.info.openid}`)
      }
    });
  })
}

exports.userinfo = (req, res) => {
  console.log('req.query.openId:', req.query.openId)
  connection.query(selectByOpenIdSql, [req.query.openId], (err, result) => {
    if (err) {
      console.log('[SELECT ERROR] - ', err.message);
    } else {
      console.log('USER INFO result = ', result)
      res.json(result);
    }
  })
}